/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 树查找
 * @param tree
 * @param id
 * @returns {null}
 */
export function deepQuery(tree, name) {
  var isGet = false
  var retNode = null
  function deepSearch(tree, name) {
    for (var i = 0; i < tree.length; i++) {
      if (tree[i].children && tree[i].children.length > 0) {
        deepSearch(tree[i].children, name)
      }
      if (name === tree[i].path || isGet) {
        isGet || (retNode = tree[i])
        isGet = true
        break
      }
    }
  }
  deepSearch(tree, name)
  return retNode
}

/**
 * 树过滤
 */

let _expandKeys_ = []
const defaultOpenKeyArr = []

export const filterTree = (val, tree, newArr = []) => {
  if (!(tree.length && val)) { // 如果搜索关键字为空直接返回源数据
    _expandKeys_ = defaultOpenKeyArr // 这块是为了记录tree的展开key可以忽略

    return tree
  }

  for (const item of tree) {
    if (item.name.includes(val)) { // 匹配到关键字的逻辑
      newArr.push(item) // 如果匹配到就在数值中添加记录

      if (item.children) _expandKeys_.push(item.key) // 这块是为了记录tree的展开key可以忽略

      continue // 匹配到了就退出循环了此时如果有子集也会一并带着
    }

    if (item.children && item.children.length) { // 如果父级节点没有匹配到就看看是否有子集，然后做递归
      _expandKeys_.push(item.key) // 这块是为了记录tree的展开key可以忽略

      const subArr = filterTree(val, item.children) // 缓存递归后的子集数组

      if (subArr && subArr.length) { // 如果子集数据有匹配到的节点
        const node = { ...item, children: subArr } // 关键逻辑，缓存父节点同时将递归后的子节点作为新值

        newArr.push(node) // 添加进数组
      }
    }
  }

  return newArr
}

export const deepClone = (obj) => {
  var copy
  // Handle the 3 simple types, and null or undefined
  if (obj == null || typeof obj !== 'object') return obj

  // Handle Date
  if (obj instanceof Date) {
    copy = new Date()
    copy.setTime(obj.getTime())
    return copy
  }

  // Handle Array
  if (obj instanceof Array) {
    if (!obj.length) return undefined
    copy = []
    for (var i = 0, len = obj.length; i < len; i++) {
      copy[i] = deepClone(obj[i])
    }
    return copy
  }

  // Handle Object
  if (obj instanceof Object) {
    copy = {}
    for (var attr in obj) {
      if (obj.hasOwnProperty(attr)) copy[attr] = deepClone(obj[attr])
    }
    return copy
  }

  throw new Error("Unable to copy obj! Its type isn't supported.")
}

/**
 * 格式化时间
 * @param {*} str
 */
export const datetime = str => {
  if (!str) return ''
  const date = new Date(str)
  const y = date.getFullYear()
  const m = date.getMonth() + 1
  const d = date.getDate()
  const h = date.getHours()
  const i = date.getMinutes()
  const s = date.getSeconds()
  return `${y}-${m < 9 ? '0' + m : m}-${d < 9 ? '0' + d : d} ${h < 9 ? '0' + h : h}:${m < 9 ? '0' + m : m}:${s < 9 ? '0' + s : s}`
}
